package risk.control.project.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import risk.control.project.config.constant.FilePath;
import risk.control.project.service.AuthCodeService;
import risk.control.project.utils.response.ResponseUtils;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@RestController
public class MAIN_000_001_001 {

    private static final Logger logger = LoggerFactory.getLogger(MAIN_000_001_001.class);

    private final AuthCodeService authCodeService;

    //文件上传下载前置接口，获取验证码
    public MAIN_000_001_001(AuthCodeService authCodeService) {
        this.authCodeService = authCodeService;
    }

    //下载支行模板信息
    @GetMapping("/main/000_001_001")
    public ResponseEntity<?> downloadFile(@RequestParam Map<String, String> params) {
        try {
            //校验请求合法性
            String authCode = params.get("authCode");
            HashMap<String, String> map = authCodeService.verifyAuthCode(authCode);
            String state = map.get("state");
            if (!state.equals("000")) {
                String msg = map.get("msg");
                String data = ResponseUtils.generateFail(msg);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            Path filePath = Paths.get(FilePath.BRANCH_TEMPLATE_FILE_DIRECTORY).resolve(FilePath.BRANCH_TEMPLATE_FILE_NAME).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (!resource.exists()) {
                // 更详细的错误信息
                String data = ResponseUtils.generateFail("文件不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            // 检查可读性
            if (!resource.isReadable()) {
                String data = ResponseUtils.generateFail("文件不可读");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            return ResponseEntity.ok()//
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)//
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")//
                    .body(resource);//
        } catch (Exception e) {
            String data = ResponseUtils.generateFail("文件下载失败");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
        }
    }
}
